<template>
  <view class="edit-page dept-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms
          ref="formRef"
          :modelValue="form"
          :rules="rules"
          labelWidth="100px">

        <!-- 上级部门 -->
        <uni-forms-item label="上级部门" name="parentId" v-if="form.parentId !== 0">
          <view class="selector dept-selector" @click="openDeptSelector">
            <view class="selector-content">
              <text class="selector-text" :class="{ placeholder: !selectedDeptName }">
                {{ selectedDeptName || '请选择上级部门' }}
              </text>
              <uni-icons type="down" size="14" color="#999"></uni-icons>
            </view>
          </view>
        </uni-forms-item>

        <!-- 部门选择抽屉 -->
        <view v-if="deptSelectorVisible" class="drawer-overlay dept-drawer-overlay" @click="closeDeptSelector">
          <view class="drawer dept-drawer" @click.stop>
            <view class="drawer-header">
              <text class="drawer-title">选择上级部门</text>
              <uni-icons type="close" size="20" @click="closeDeptSelector"></uni-icons>
            </view>
            <view class="drawer-body">
              <da-tree
                  ref="deptTreeRef"
                  :data="deptOptions"
                  :show-checkbox="false"
                  :show-radio-icon="true"
                  :default-checked-keys="form.parentId ? [form.parentId] : []"
                  :value-field="'deptId'"
                  :label-field="'deptName'"
                  :children-field="'children'"
                  :indent="20"
                  @change="handleDeptSelect">
              </da-tree>
            </view>
            <view class="drawer-footer">
              <button class="btn btn-cancel" @click="closeDeptSelector">取消</button>
              <button class="btn btn-confirm" @click="confirmDeptSelect">确定</button>
            </view>
          </view>
        </view>

        <uni-forms-item label="部门名称" name="deptName" required>
          <uni-easyinput
              v-model="form.deptName"
              placeholder="请输入部门名称"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="显示排序" name="orderNum" required>
          <uni-number-box
              v-model="form.orderNum"
              :min="0"
              :max="999"
              :disabled="!canEdit">
          </uni-number-box>
        </uni-forms-item>

        <uni-forms-item label="负责人" name="leader">
          <uni-easyinput
              v-model="form.leader"
              placeholder="请输入负责人"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="联系电话" name="phone">
          <uni-easyinput
              v-model="form.phone"
              placeholder="请输入联系电话"
              type="tel"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="邮箱" name="email">
          <uni-easyinput
              v-model="form.email"
              placeholder="请输入邮箱"
              type="email"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="部门状态" name="status">
          <BottomSelect
              v-model="form.status"
              :options="statusOptions"
              value-field="value"
              label-field="text"
              placeholder="请选择部门状态"
              title="选择部门状态"
              :disabled="!canEdit">
          </BottomSelect>
        </uni-forms-item>

      </uni-forms>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <view class="action-buttons">
        <view
            v-if="!isView"
            class="cancel-btn"
            @click="handleBack">
          取消
        </view>
        <view
            v-if="!isView"
            class="submit-btn"
            @click="handleSubmit">
          {{ pageType === 'add' ? '确认新增' : '保存修改' }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, nextTick, onMounted, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {addDept, getDept, listDept, listDeptExcludeChild, updateDept} from '@/api/system/dept'
import {handleTree} from '@/utils/ruoyi'
import DaTree from '@/components/da-tree/index.vue'
import {BottomSelect} from '@/components/select'

// 使用统一组件导入

const {proxy} = getCurrentInstance()

// 页面参数
const pageType = ref('add')
const deptId = ref(null)
const parentId = ref(0)
const submitting = ref(false)

// 计算属性
const pageTitle = computed(() => {
  switch (pageType.value) {
    case 'add':
      return '新增部门'
    case 'edit':
      return '编辑部门'
    case 'view':
      return '查看部门'
    default:
      return '部门管理'
  }
})

const isView = computed(() => pageType.value === 'view')
const canEdit = computed(() => pageType.value === 'add' || pageType.value === 'edit')

// 表单数据
const form = reactive({
  deptId: undefined,
  parentId: 0,
  deptName: '',
  orderNum: 0,
  leader: '',
  phone: '',
  email: '',
  status: '0'
})

// 表单验证规则
const rules = {
  deptName: {
    rules: [
      {required: true, errorMessage: '部门名称不能为空'},
      {minLength: 2, maxLength: 30, errorMessage: '部门名称长度在2到30个字符'}
    ]
  },
  orderNum: {
    rules: [
      {required: true, errorMessage: '显示排序不能为空'}
    ]
  },
  phone: {
    rules: [
      {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, errorMessage: '请输入正确的手机号码'}
    ]
  },
  email: {
    rules: [
      {format: 'email', errorMessage: '请输入正确的邮箱地址'}
    ]
  }
}

// 选项数据
const statusOptions = ref([
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
])

// 部门选项和选中名称
const deptOptions = ref([])
const deptSelectorVisible = ref(false)
const selectedDeptName = ref('')
const tempSelectedDeptId = ref(null)

// 组件引用
const formRef = ref()

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {
  // 获取页面参数
  pageType.value = options.mode || options.type || 'add'
  deptId.value = options.deptId || options.id || null
  parentId.value = options.parentId || 0

  // 设置页面标题
  uni.setNavigationBarTitle({
    title: pageTitle.value
  })

  // 新增子部门时设置父部门
  if (parentId.value) {
    form.parentId = parseInt(parentId.value)
  }
})

// 页面初始化
onMounted(() => {
  // 获取部门树
  getDeptTree()

  // 如果是编辑模式，获取部门信息
  if (pageType.value === 'edit' && deptId.value) {
    // 延迟获取，确保页面完全初始化
    nextTick(() => {
      getDeptInfo()
    })
  }
})

// 获取部门树
async function getDeptTree() {
  try {
    let response
    if (pageType.value === 'edit' && deptId.value) {
      // 编辑时排除自身及子部门
      response = await listDeptExcludeChild(deptId.value)
    } else {
      // 新增时获取所有部门
      response = await listDept()
    }

    if (response.code === 200) {
      deptOptions.value = handleTree(response.data, "deptId")
    } else {
      console.error('获取部门树失败，响应码:', response.code, '消息:', response.msg)
    }
  } catch (error) {
    console.error('获取部门树失败:', error)
    proxy.$modal.showToast('获取部门树失败')
  }
}

// 获取部门信息
async function getDeptInfo() {
  try {
    const response = await getDept(deptId.value)

    if (response.code === 200) {
      Object.assign(form, response.data)

      // 设置选中的部门名称
      if (form.parentId && form.parentId !== 0) {
        const findDeptName = (depts, targetId) => {
          for (const dept of depts) {
            if (dept.deptId === targetId) {
              return dept.deptName
            }
            if (dept.children && dept.children.length > 0) {
              const found = findDeptName(dept.children, targetId)
              if (found) return found
            }
          }
          return ''
        }
        selectedDeptName.value = findDeptName(deptOptions.value, form.parentId)
      }
    } else {
      console.error('获取部门信息失败，响应码:', response.code, '消息:', response.msg)
    }
  } catch (error) {
    console.error('获取部门信息失败:', error)
    proxy.$modal.showToast('获取部门信息失败')
  }
}

// 打开部门选择器
function openDeptSelector() {
  if (!canEdit.value) return
  deptSelectorVisible.value = true
  tempSelectedDeptId.value = form.parentId
}

// 关闭部门选择器
function closeDeptSelector() {
  deptSelectorVisible.value = false
}

// 处理部门选择
function handleDeptSelect(deptId, node) {
  tempSelectedDeptId.value = deptId
}

// 确认部门选择
function confirmDeptSelect() {
  if (tempSelectedDeptId.value) {
    form.parentId = tempSelectedDeptId.value
    // 根据选中的ID查找部门名称
    const findDeptName = (depts, targetId) => {
      for (const dept of depts) {
        if (dept.deptId === targetId) {
          return dept.deptName
        }
        if (dept.children && dept.children.length > 0) {
          const found = findDeptName(dept.children, targetId)
          if (found) return found
        }
      }
      return ''
    }
    selectedDeptName.value = findDeptName(deptOptions.value, tempSelectedDeptId.value)
    console.log('已选择上级部门:', selectedDeptName.value, 'ID:', tempSelectedDeptId.value)
  }
  closeDeptSelector()
}

// 提交表单
async function handleSubmit() {
  if (submitting.value) return

  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }

    submitting.value = true

    let response
    if (pageType.value === 'add') {
      response = await addDept(form)
    } else {
      response = await updateDept(form)
    }

    if (response.code === 200) {
      proxy.$modal.showToast(pageType.value === 'add' ? '新增成功' : '修改成功')
      setTimeout(() => {
        handleBack()
      }, 1500)
    } else {
      proxy.$modal.showToast(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    proxy.$modal.showToast('操作失败')
  } finally {
    submitting.value = false
  }
}

// 返回
function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/edit-page.scss';

// 部门编辑页面特定样式
.dept-edit-page {
  // 可以添加部门特有的样式覆盖
}
</style>